﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace GEPSCodeTemplate
{
    public partial class ParamSetForm : Form
    {
        private Parser _parser;
        private Param _param;

        private ParamSetForm(string content, string initValue)
        {
            InitializeComponent();
            _parser = new Parser(content);
            txtValue.Text = initValue;
        }

        private bool IsParamExist()
        {
            return _parser.Params.ContainsKey(txtName.Text);
        }

        public static string GetParamString(string content, string initValue)
        {
            ParamSetForm oForm = new ParamSetForm(content, initValue);
            DialogResult dr = oForm.ShowDialog();
            if (dr == DialogResult.OK)
            {
                return Param.ParamStartFlag + oForm._param.Name + Param.ParamSpliter
                    + oForm._param.Descripe + Param.ParamSpliter
                    + oForm._param.Value + Param.ParamEndFlag;
            }
            else
            {
                return initValue;
            }
        }

        private void UpdateParam()
        {
            if (IsParamExist())
            {
                _param = _parser.Params[txtName.Text];
            }
            else
            {
                _param.Name = txtName.Text;
                _param.Value = txtValue.Text;
                _param.Descripe = txtDescribe.Text;
            }
        }

        private void txtName_TextChanged(object sender, EventArgs e)
        {
            if (IsParamExist())
            {
                lblHint.Visible = true;
                txtDescribe.Enabled = false;
                txtValue.Enabled = false;
            }
            else
            {
                lblHint.Visible = false;
                txtDescribe.Enabled = true;
                txtValue.Enabled = true;
            }
            UpdateParam();
        }

        private void txtValue_TextChanged(object sender, EventArgs e)
        {
            UpdateParam();
        }

        private void txtDescribe_TextChanged(object sender, EventArgs e)
        {
            UpdateParam();
        }

        private void SetParamForm_FormClosing(object sender, FormClosingEventArgs e)
        {

            DialogResult = (string.IsNullOrEmpty(_param.Name)) ? DialogResult.Cancel : DialogResult.OK;
        }
    }
}
